//
//  NoteListViewController.m
//  NanNote
//
//  Created by 郑楠 on 15/5/19.
//  Copyright (c) 2015年 ___NANteam___. All rights reserved.
//

#import "NoteListViewController.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface NoteListViewController ()

@property(nonatomic, retain)NSMutableArray *modelArray;

@property(nonatomic, retain)UITableView *noteTblView;

@property(nonatomic, retain)CoreDataManager *dataManager;

@property(nonatomic, retain)UISearchBar *searchBar;
// 添加按钮
@property(nonatomic, retain)UIBarButtonItem *addBtn;
// 删除按钮
@property(nonatomic, retain)UIBarButtonItem *deleteBtn;
// 编辑完成
@property(nonatomic, retain)UIBarButtonItem *okayBtn;
// 抽屉按钮
@property(nonatomic, retain)UIBarButtonItem *drawBtn;
// 抽屉View
@property(nonatomic, retain)DrawerView *drawView;
//抽屉状态 0:关闭状态  1:展开状态
@property(nonatomic, assign)BOOL isDrawed;

@end

@implementation NoteListViewController

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Note List";
    self.isDrawed = NO;
    self.addBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"add.png"] style:UIBarButtonItemStylePlain target:self action:@selector(addNoteBtnClick:)];
    
    self.deleteBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"minus.png"] style:UIBarButtonItemStylePlain target:self action:@selector(deleteNoteBtnClick:)];
    
    self.okayBtn = [[UIBarButtonItem alloc] initWithTitle:@"OK" style:UIBarButtonItemStyleDone target:self action:@selector(okayBtnClick:)];
    
    self.drawBtn = [[UIBarButtonItem alloc] initWithTitle:@"抽屉" style:UIBarButtonItemStylePlain target:self action:@selector(drawBtnClick:)];
    
    self.drawView = [[DrawerView alloc] initWithFrame:CGRectMake(-10, 0, 10, HEIGHT)];
    self.drawView.delegate = self;
    [self.view addSubview:self.drawView];
    // 添加按钮
    self.navigationItem.rightBarButtonItems = @[self.addBtn, self.deleteBtn];
    self.navigationItem.leftBarButtonItem = self.drawBtn;
    
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, 30)];
    self.searchBar.delegate = self;
    [self.searchBar setShowsCancelButton:YES animated:YES];
    self.noteTblView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    self.noteTblView.dataSource = self;
    self.noteTblView.delegate = self;
    self.noteTblView.tableHeaderView = self.searchBar;
    self.searchBar.searchBarStyle = UISearchBarStyleDefault;
    self.noteTblView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.noteTblView];
    
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    //增加监听，当键退出时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    
}

- (void)dataFromNoteEntity {
    self.dataManager = [CoreDataManager defaultCoreDataManager];
    // 查询
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"NoteEntity" inManagedObjectContext:self.dataManager.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"deleteFlg == 0"];
    if (self.searchBar.text != nil && ![self.searchBar.text isEqualToString:@""]) {
        predicate = [NSPredicate predicateWithFormat:@"deleteFlg == 0 and noteContent contains %@", self.searchBar.text];
    }
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastUpdTime"
                                                                   ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [self.dataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects.count == 0) {
        NSLog(@"dataFromNoteEntity 0条");
    } else {
        self.modelArray = [NSMutableArray arrayWithArray:fetchedObjects];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.modelArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuse];
    }
    NoteEntity *note = self.modelArray[indexPath.row];
    cell.textLabel.text = note.noteContent;
    cell.detailTextLabel.text = note.lastUpdTime;
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    if ([note.noteBgColor integerValue] == myYellowColor){
        [cell setBackgroundColor:[UIColor yellowColor]];
    } else if ([note.noteBgColor integerValue] == myOrangeColor) {
        [cell setBackgroundColor:[UIColor orangeColor]];
    } else if ([note.noteBgColor integerValue] == myCyanColor) {
        [cell setBackgroundColor:[UIColor cyanColor]];
    } else if ([note.noteBgColor integerValue] == myGreenColor) {
        [cell setBackgroundColor:[UIColor greenColor]];
    } else if ([note.noteBgColor integerValue] == myGrayColor) {
        [cell setBackgroundColor:[UIColor grayColor]];
    } else if ([note.noteBgColor integerValue] == myWhiteColor) {
        [cell setBackgroundColor:[UIColor whiteColor]];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NoteViewController *noteVC = [[NoteViewController alloc] init];
    noteVC.lastUpdTime = [self.modelArray[indexPath.row] lastUpdTime];
    [self.navigationController pushViewController:noteVC animated:YES];
}
// 添加按钮
- (void)addNoteBtnClick:(UIBarButtonItem *)btn {
    NoteViewController *noteVC = [[NoteViewController alloc] init];
    [self.navigationController pushViewController:noteVC animated:YES];
}
// 删除按钮
- (void)deleteNoteBtnClick:(UIBarButtonItem *)btn {
    [self.noteTblView setEditing:YES animated:YES];
    [self updateBarButtons];
}
// 完成按钮
- (void)okayBtnClick:(UIBarButtonItem *)btn {
    [self.noteTblView setEditing:NO animated:YES];
    self.navigationItem.rightBarButtonItems = @[self.addBtn, self.deleteBtn];
}
// 抽屉按钮
- (void)drawBtnClick:(UIBarButtonItem *)btn {
    self.isDrawed = !self.isDrawed;
    if (self.isDrawed) {
        [UIView animateWithDuration:2 animations:^{
        } completion:^(BOOL finished) {
            self.drawView.frame = CGRectMake(0, 0, 150, HEIGHT);
            self.noteTblView.frame = CGRectMake(150, 0, WIDTH, HEIGHT);
        }];
    } else {
        [UIView animateWithDuration:2 animations:^{
            
        } completion:^(BOOL finished) {
            self.drawView.frame = CGRectMake(0, 0, 0, HEIGHT);
            self.noteTblView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        }];
    }
}

-(void)pushToTrash {
    TrashViewController *trashVC = [[TrashViewController alloc] init];
    [self.navigationController pushViewController:trashVC animated:YES];
}

// 删除对应的note
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NoteEntity *selectedNote = self.modelArray[indexPath.row];
        [self.modelArray removeObjectAtIndex:(indexPath.row)];
        // 接下操作cell
        [self.noteTblView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationRight];
        
        // 查询
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"NoteEntity" inManagedObjectContext:self.dataManager.managedObjectContext];
        [fetchRequest setEntity:entity];
        // Specify criteria for filtering which objects to fetch
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"lastUpdTime == %@", selectedNote.lastUpdTime];
        [fetchRequest setPredicate:predicate];
        
        NSError *error = nil;
        NSArray *fetchedObjects = [self.dataManager.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        if (fetchedObjects.count == 0) {
            NSLog(@"要删除的数据是:0条");
        } else {
            NoteEntity *deletedNote = fetchedObjects[0];
            deletedNote.deleteFlg = @"1";
            [self.dataManager saveContext];
        }
    }
}
// 更新导航栏按钮
-(void)updateBarButtons
{
    if (self.noteTblView.editing==YES) {
        self.navigationItem.rightBarButtonItems = @[self.addBtn, self.okayBtn];
    }
    else {

    }
}
// 点击键盘上的搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self dataFromNoteEntity];
    [self.noteTblView reloadData];
}
// 点击搜索栏上取消按钮时候
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    self.searchBar.text = @"";
    [self.searchBar resignFirstResponder];
    [self dataFromNoteEntity];
    [self.noteTblView reloadData];
}

- (void)viewDidAppear:(BOOL)animated {
    [self dataFromNoteEntity];
    [self.noteTblView reloadData];
}

//当键盘出现或改变时调用
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    //获取键盘的高度
    NSDictionary *userInfo = [aNotification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    NSInteger height = keyboardRect.size.height;
    self.noteTblView.frame = CGRectMake(0, 0, WIDTH, HEIGHT - height);
}

//当键退出时调用
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.noteTblView.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
}

// 编辑
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    [super setEditing:editing animated:animated];
    
    [self.noteTblView setEditing:editing animated:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
